package sk.fiit.icp.service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import sk.fiit.icp.data.Event;
import sk.fiit.icp.data.Events;
import sk.fiit.icp.data.EventsDao;

public class EventServiceImpl implements EventService {
	EventsDao eventsDao;

	SessionService sessionService;

	public void setEventsDao(EventsDao eventsDao) {
		this.eventsDao = eventsDao;
	}

	public void setSessionService(SessionService sessionService) {
		this.sessionService = sessionService;
	}

	public List<Event> getEvents() {
		List<Events> eventsDB = eventsDao.findAllByUser(sessionService.getUsers());
		List<Event> events = new ArrayList<Event>(eventsDB.size());
		Event event;
		for (Events eventDB : eventsDB) {
			event = new Event(eventDB, null, new LinkedList<Event>());
			events.add(event);
		}
		for (Event setEvent : events) {
			for (Event eventTemp : events) {
				if (eventTemp.getEvents() != null && eventTemp.getEvents().getIdevent().equals(setEvent.getIdevent())) {
					setEvent.getChildrens().add(eventTemp);
				}
				if (setEvent.getEvents() != null && setEvent.getEvents().getIdevent().equals(eventTemp.getIdevent())) {
					setEvent.setParent(eventTemp);
				}
			}
		}

		return events;

	}

	public void saveEvents(List<Event> list) {
		for (Event event : list) {
			saveEvents(event.getChildrens());
			if (event.getParent() != null) {
				event.getEventDB().setEvents(event.getParent().getEventDB());
			}
			eventsDao.update(event.getEventDB());
		}

	}

}
